<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <div class="card-header">
          <h2>登录</h2>
        </div>
      </template>
      
      <el-form :model="loginForm" :rules="rules" ref="formElRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleLogin" :loading="loading">登录</el-button>
          <el-button @click="$router.push('/register')">注册</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'

export default {
  name: 'Login',
  setup() {
    const router = useRouter()
    const formElRef = ref(null)
    const loginForm = reactive({
      username: '',
      password: ''
    })
    const loading = ref(false)
    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
      ]
    }

    const handleLogin = async () => {
      if (!formElRef.value) return
      formElRef.value.validate(async (valid) => {
        if (valid) {
          loading.value = true
          try {
            const response = await axios.post('/api/auth/login', loginForm)
            const { accessToken, userId, username, email } = response.data
            
            localStorage.setItem('token', accessToken)
            localStorage.setItem('user', JSON.stringify({ userId, username, email }))
            
            ElMessage.success('登录成功')
            router.push('/')
          } catch (error) {
            ElMessage.error(error.response?.data?.message || '登录失败')
          } finally {
            loading.value = false
          }
        } else {
          console.log('表单验证失败!')
          return false
        }
      })
    }

    return {
      loginForm,
      loading,
      rules,
      handleLogin,
      formElRef
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f7fa;
}

.login-card {
  width: 400px;
}

.card-header {
  text-align: center;
}

.el-button {
  margin-right: 10px;
}
</style> 